package com.alibaba.org.controller;

import com.alibaba.basic.query.BaseQuery;
import com.alibaba.basic.util.AjaxResult;
import com.alibaba.basic.util.PageList;
import com.alibaba.org.domain.Emp;
import com.alibaba.org.service.impl.EmpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/emp")
public class EmpCollecter {
    // 注入
    @Autowired
    private EmpServiceImpl empService;

    // 员工查询所有
    @GetMapping
    public List<Emp> findAll() {
        return empService.findAll();
    }

    // 根据id查询
    @GetMapping("/{id}")
    public Emp findById(@PathVariable("id") Long id) {
        return empService.findById(id);
    }

    // 根据id删除
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long id) {
        try {
            empService.remove(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    // 新增和修改
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Emp emp) {
        try {
            // 新增和修改的Id不一样
            if (emp.getId()==null){
                empService.add(emp);
            } else {
                empService.update(emp);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }

    // 分页查询
    @PostMapping
    public PageList<Emp> queryPage(@RequestBody BaseQuery baseQuery){
        return empService.query(baseQuery);
    }
    @PatchMapping
    public AjaxResult patchRemove(@RequestBody List<Long> ids) {
        try {
            empService.patchRemove(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }
}
